<template>
  <view class="chat-wrapper">
    <view :style="{'padding-bottom': `${60+inputBottom}px`}" class="container">
      <image
          class="my-bg"
          mode="scaleToFill"
          src="https://ai-sbbs.xyz/api/profile/upload/2024/07/01/216ecf4ef90549a1b0d6b8cd648786f9.png"
      />

      <scroll-view
          id="scrollview"
          :scroll-top="scrollTop"
          :style="{height:scrollViewHeight+'px'}"
          class="Scroll"
          scroll-y
      >
        <view v-for="(item, index) in chatList" :id="'danmu-' + index" :key="index" class="chatList">
          <view :class="item.role == 'assistant' ? 'mes-left' : 'mes-right'" class="message">
            <tui-image-group
                :imageList="item.role == 'assistant' ?imageList2:imageList"
                height="60rpx"
                radius="20rpx"
                width="60rpx"
            ></tui-image-group>
            <view v-if="item.content" class="mes-content">
              <!--              <u-parse :content="item.content" className="parse" @navigate="toSend"></u-parse>-->
              <view v-if="item.content.includes('\n')">
                <view v-for="(it,idx) in chooseHtml(item.content)" :key="idx" class="border-b">
                  {{ it }}
                </view>
              </view>
              <view v-else>
                {{ item.content }}
              </view>

              <view v-if="item.showYin" class="yin-yong">
                <view class="tit">
                  <image class="icon" src="@/static/imgs/yin-yong.png"></image>
                  <text class="msg">引用</text>
                  <view class="line"></view>
                </view>

                <view class="content">
                  <view v-for="item in 11" class="item">
                    <image class="icon" src="@/static/imgs/wenjian.png"></image>
                    <text class="msg">说明.txt</text>
                  </view>

                </view>
                <view class="tips">
                  <view class="t">11条引用</view>
                </view>
              </view>

            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view :style="{bottom: inputBottom+'px'}" class="bottom-textarea">
      <view class="btn-box">
        <view class="btn" style="margin-right: 20rpx;" @click="toShengChen">
          <image class="icon" src="@/static/imgs/bazi.png"></image>
          随机六爻
        </view>
        <view>
          <tui-input v-model="userInput[0]" :maxlength="3" inputBorder
                     padding="10rpx" style="width: 100rpx;text-align: center;margin-right: 20rpx;"></tui-input>
        </view>
        <view>
          <tui-input v-model="userInput[1]" :maxlength="3" inputBorder
                     padding="10rpx" style="width: 100rpx;text-align: center;margin-right: 20rpx;"></tui-input>
        </view>
        <view>
          <tui-input v-model="userInput[2]" :maxlength="3" inputBorder
                     padding="10rpx" style="width: 100rpx;text-align: center;margin-right: 20rpx;"></tui-input>
        </view>
      </view>

      <view class="content">

        <view class="textarea-container">
          <!--          <view class="number-content">-->

          <!--            -->
          <!--          </view>-->

          <textarea
              v-model.trim="userInput[3]"
              :adjust-position="false"
              :auto-height="true"
              :cursor-spacing="10"
              :fixed="true"
              :maxlength="-1"
              :show-confirm-bar="false"
              class="textarea"
              placeholder="请文明发言"
              @blur="blurTextarea"
              @focus="focusTextarea"

          />

        </view>

<!--            :loading="btnLoading"-->
        <tui-form-button
            :disabled="btnLoading"
            background="rgb(230, 162, 60)"
            height="60rpx"
            preventClick
            style="margin-left: 15rpx;font-size: 30rpx"
            width="90rpx"
            @click="sendMsg"
        >发送
        </tui-form-button>

      </view>

      <!--      <tui-icon @click="askChatGPT" name="add" size="28" class="tul-icon-wr"></tui-icon>-->

      <!-- <button class="primary-btn">记录</button> -->
    </view>

    <tui-modal :show="modalShow" custom>
      <view class="tui-modal-custom">
        <tui-input v-model="userInput[0]" :maxlength="3" inputBorder></tui-input>
        <tui-input v-model="userInput[1]" :maxlength="3" inputBorder></tui-input>
        <tui-input v-model="userInput[2]" :maxlength="3" inputBorder></tui-input>
      </view>
      <view class="tui-modal-custom">
        <tui-form-button :size="28" background="rgb(230, 162, 60)" height="72rpx" shape="circle"
                         style="margin-right: 15rpx;"
                         @click="changeModal">确定
        </tui-form-button>
        <tui-form-button :size="28" background="rgb(230, 162, 60)" height="72rpx" shape="circle"
                         @click="toShengChen">随机六爻
        </tui-form-button>
      </view>
    </tui-modal>
  </view>
</template>

<script>
import {commonStorage} from "@/utils/common.js";
import uParse from '@/components/u-parse/u-parse.vue'
import {getCozeKeyApi, userInfoApi} from "@/apis/user";

import {yfgpaipanApi} from "@/apis/qiuqian.js";

export default {
  components: {uParse},
  data() {
    return {
      apiKey: null,

      imageList: [
        {
          id: 1,
          src: "https://cdn.uviewui.com/uview/album/1.jpg"
        }
      ],

      imageList2: [
        {
          id: 1,
          src: "https://ai-sbbs.xyz/api/profile/upload/2024/10/home_selected.png"
          // src: "../../../static/tabs/home_selected.png"
        }
      ],

      chatList: [],
      userInfo: {},
      scrollViewHeight: 0,
      itemAverageHeight: 500, //每条数据平均高度，为确保能滚到底部，可以设置大一些
      scrollTop: 1000,
      inputBottom: 15,
      scroll_danmu_id: "danmu-16",
      userInput: [null, null, null, null],
      currentIndex: 0,
      userInputInfo: null,
      modalShow: false,
      btnLoading: false,

    };
  },
  async mounted(option) {
    await this.getToken();
    this.getClineHeight();
    const lineStyle = `
      font-size: 12px;
      color: #007aff;
      text-decoration: underline;
    `
    const liStyle = `
      font-size: 10px;
      margin-top:5px;

    `
    this.chatList.push({
      role: "assistant",
      showYin: false,
      "content_type": "text",
      content: `哈喽啊，填入 3 组数字我来为你算算`
    });
    /**
     *  <li style="${liStyle}">
     *         <a style="${lineStyle}" href="七爷，我最近桃花运怎么样？">七爷，我最近桃花运怎么样？</a>
     *       </li>
     *       <li style="${liStyle}">
     *         <a style="${lineStyle}" href="七爷，我最近打牌可以坐那个位置？">七爷，我最近打牌可以坐那个位置？</a>
     *       </li>
     *       <li style="${liStyle}">
     *         <a style="${lineStyle}" href="七爷，最近有没有赚钱的机会？">七爷，最近有没有赚钱的机会？</a>
     *       </li>
     * */

    this.getUserInfo();

    setTimeout(() => {
      this.scroll_danmu_id = "danmu-16";
    }, 100);

    this.inputBottom = uni.getSystemInfoSync().safeAreaInsets.bottom
  },
  methods: {
    chooseHtml(val) {
      return val.split('\n')
    },
    sendMsg() {
      // if (!this.userInput[3]) {
      //   return
      // }

      if (this.userInput[0] && this.userInput[1] && this.userInput[2]) {
        if (!this.isNumber(this.userInput[0]) || !this.isNumber(this.userInput[1]) || !this.isNumber(this.userInput[2])) {
          uni.showToast({
            title: '请填写000-999之间的数字',
            icon: 'none'
          })
          return;
        }
        if (!this.is3Len(this.userInput[0]) || !this.is3Len(this.userInput[1]) || !this.is3Len(this.userInput[2])) {
          uni.showToast({
            title: '请填写3位数数字',
            icon: 'none'
          })
          return;
        }
      } else {
        if (!this.userInput[3]) {
          return
        }
      }
      this.askChatGPT()
    },
    changeModal() {
      this.modalShow = !this.modalShow
      if (!this.modalShow) {
        if (!this.userInput[0] || !this.userInput [1] || !this.userInput[2]) {
          uni.showToast({
            title: '请填写完整六爻信息',
            icon: 'none'
          })
          return;
        }

        if (!this.isNumber(this.userInput[0]) || !this.isNumber(this.userInput[1]) || !this.isNumber(this.userInput[2])) {
          uni.showToast({
            title: '请填写000-999之间的数字',
            icon: 'none'
          })
          return;
        }
        if (!this.is3Len(this.userInput[0]) || !this.is3Len(this.userInput[1]) || !this.is3Len(this.userInput[2])) {
          uni.showToast({
            title: '请填写3位数数字',
            icon: 'none'
          })
          return;
        }
        this.askChatGPT()
      }
    },
    toShengChen() {
      this.userInput = [this.generateThreeDigitNumber(), this.generateThreeDigitNumber(), this.generateThreeDigitNumber()]
      // this.askChatGPT()

    },
    toSend(href, e) {
      console.log(href, e)
      this.userInput = href
      this.askChatGPT()
    },
    async getToken() {
      let {code, data} = await getCozeKeyApi();
      if (code == 1) {
        this.apiKey = data.secretKey;
      }
    },

    getClineHeight() {
      let _this = this;
      const res = uni.getSystemInfo({
        success: res => {
          _this.scrollViewHeight = res.windowHeight - 50;
        }
      });
    },
    async getUserInfo() {
      let loginInfo =
          commonStorage.getStorageSync("userInfo") &&
          JSON.parse(commonStorage.getStorageSync("userInfo"));
      if (loginInfo) {
        let {code, data} = await userInfoApi(loginInfo.userId);
        if (code == 1) {
          this.userInfo = data;
          // let sex = data.gender == 1 ? "男" : "女";
          this.baziInfo();
          // let query = `我的名字叫${data.userName},性别为${sex}，出生地点为${data.birthPlace},出生时间为${data.birthDate}`;
          // this.userInputInfo = query;
        }
      }
    },

    async baziInfo() {
      let arrs = JSON.parse(JSON.stringify(this.userInfo.birthDate));
      let arr2 = arrs.split(" ")[0];
      let {code, data} = await yfgpaipanApi({
        name: this.userInfo.userName,
        sex: this.userInfo.gender,
        type: 1,
        year: arr2.split("-")[0],
        month: parseInt(arr2.split("-")[1]),
        day: parseInt(arr2.split("-")[2]),
        hours: 12,
        minute: 0,
        sect: 1,
        zhen: 2
      });
      if (code == 1 && data.baziInfo) {
        let query = `【${arr2.split("-")[0]}.${arr2.split("-")[1]}.${
            arr2.split("-")[2]
        } 年柱：${data.baziInfo.bazi[0]} 月柱：${data.baziInfo.bazi[1]} 日柱：${
            data.baziInfo.bazi[2]
        } 时柱：${data.baziInfo.bazi[3]}】`;
        this.userInputInfo = query;
      }
    },
    isNumber(value) {
      return /^-?\d+(\.\d+)?$/.test(value);
    },
    is3Len(val) {
      return val.length === 3
    },
    generateThreeDigitNumber() {
      return Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    },
    async askChatGPT() {

      this.btnLoading = true;
      console.log(this.userInput.join(' '))
      // return
      let _this = this;
      _this.chatList.push({
        role: "user",
        content: this.userInput.join(' '),
        "content_type": "text"
      });


      // #ifdef MP-WEIXIN

      const requestTask = uni.request({
        url: "/codeApi", // 请求地址
        method: "POST",
        stream: true,
        withCredentials: true,
        data: JSON.stringify({
          bot_id: "7424478657823178803",
          user_id: _this.userInfo.userId,
          query: `${_this.userInputInfo},${_this.userInput.join(' ')}`,
          stream: true,
          additional_messages: _this.chatList,
          auto_save_history: true,

        }),
        header: {
          "Content-Type": "application/json",
          Connection: "keep-alive",
          Authorization: 'Bearer pat_OFHPrgjA8NRfKhVHhx8L7L3hwIs7A4cvZ23D5sxrl06VJuI8X5Gp01J7aRgjxbJB',//`Bearer ${this.apiKey}`,
          Accept: "*/*"
        },
        responseType: "arraybuffer",
        enableChunked: true, // 开启流传输
        success: async response => {
          if (response) {

            _this.loading = false;
            _this.chatList[_this.chatList.length - 1].showYin = true
          }
        },
        fail: err => {
          _this.loading = false;
          // reject(err);
        }
      });
      _this.chatList.push({
        role: "assistant",
        content: "",
        showYin: false,
        "content_type": "text"
      });
      requestTask.onHeadersReceived(function (res) {
      });
      requestTask.onChunkReceived(async response => {
        // 兼容小程序写法
        let reader = decodeURIComponent(
            escape(String.fromCharCode(...new Uint8Array(response.data)))
        );

        if (reader === 'data:{"event":"done"}') {
          return;
        }
        reader = reader.replaceAll("data:", "");
        reader = reader.split(/[(\r\n)\r\n]+/);
        reader = new Set(reader)
        if (reader[0] && reader[0] === "event:conversation.message.delta") {

          for (const it of reader) {
            if (it === 'event:conversation.message.completed') {
              break; // 遇到特定项时中断循环
            }
            try {
              if (it) {
                let item = JSON.parse(it);
                if (item.type == "answer") {
                  let text = item.content;

                  _this.chatList[_this.chatList.length - 1].content += text;


                  _this.scrollTop = _this.scrollViewHeight + 200;

//
//                   return
//                   let regex = /\n\n/g;
//                   if (text.match(regex)) {
//                     let matches = text.match(regex) || [];
//                     // console.log('匹配到换行符————————————————————————')
//                     // 检查是否在文本的开始位置
//                     if (text.startsWith('\n\n')) {
//                       // console.log('连续的换行符在文本的前面。');
//                       _this.chatList.push({
//                         role: "system",
//                         content: ''
//                       });
//
//                       _this.chatList[_this.chatList.length - 1].content += text;
//
//                     }
//
// // 检查是否在文本的结束位置（注意：这可能需要一些额外的逻辑）
//                     if (text.endsWith('\n\n') && text.lastIndexOf('\n\n') === text.length - 2) {
//                       // console.log('连续的换行符在文本的后面。');
//
//                       _this.chatList[_this.chatList.length - 1].content += text;
//                       _this.chatList.push({
//                         role: "system",
//                         content: ''
//                       });
//
//                     }
//
// // 如果以上两个条件都不满足，则假定连续的换行符在文本的中间
//                     if (matches.length > 0 && !text.startsWith('\n\n') && !(text.endsWith('\n\n') && text.lastIndexOf('\n\n') === text.length - 2)) {
//                       // console.log('连续的换行符在文本的中间。',);
//                       const item = text.split('\n\n')
//                       _this.chatList[_this.chatList.length - 1].content += item[0];
//
//                       _this.chatList.push({
//                         role: "system",
//                         content: item[1]
//                       });
//                     }
//                   } else {
//                     _this.chatList[_this.chatList.length - 1].content += text;
//                   }
                  //  if (text == "\n\n") {
                  //   _this.chatList.push("");
                  //   _this.chatList[_this.chatList.length - 1].content += text;
                  // } else {
                  //    _this.chatList[_this.chatList.length - 1].content += text;
                  // }

                  // _this.scrollTop = _this.scrollViewHeight + 200;
                }
              }
            } catch (e) {

            }
          }
          // reader.forEach(item => {
          //
          // });
        }
      });
      // #endif
      // #ifdef H5
      fetch('https://api.coze.cn/v3/chat', {
        method: 'POST',
        headers: {
          "Content-Type": "application/json",
          Connection: "keep-alive",
          Authorization: 'Bearer pat_OFHPrgjA8NRfKhVHhx8L7L3hwIs7A4cvZ23D5sxrl06VJuI8X5Gp01J7aRgjxbJB',//`Bearer ${this.apiKey}`,
          Accept: "*/*"
        },
        body: JSON.stringify({
          bot_id: "7424478657823178803",
          user_id: _this.userInfo.userId,
          query: `${_this.userInputInfo},${_this.userInput.join(' ')}`,
          stream: true,
          additional_messages: _this.chatList,
          auto_save_history: true,
        })
      })
          .then(response => {
            if (response.body) {
              _this.chatList.push({
                role: "assistant",
                content: "",
                showYin: false,
                "content_type": "text"
              });
              return response.body;
            }
            return response.text();
          })
          .then(data => {
            // 处理流式数据
            if (data instanceof ReadableStream) {
              const reader = data.getReader();

              function read() {
                reader.read().then(({done, value}) => {
                  if (done) {
                    console.log('Stream complete');
                    _this.btnLoading = false
                    return;
                  }
                  const chunk = new TextDecoder().decode(value, {stream: true});
                  let reader = chunk
                  if (reader === 'data:{"event":"done"}') {
                    _this.btnLoading = false
                    return;
                  }
                  if (reader.search('event:conversation.message.delta') !== -1) {
                    reader = reader.replaceAll("data:", "");
                    reader = reader.split(/[(\r\n)\r\n]+/);
                    reader = new Set(reader)
                    console.log(reader)
                    reader.forEach(item => {
                      if (item) {
                        try {
                          item = JSON.parse(item);
                          if (item.type == "answer") {
                            let text = item.content;

                            _this.chatList[_this.chatList.length - 1].content += text;
                            _this.scrollTop = _this.scrollViewHeight + 200;
                          }
                        } catch (e) {

                        }
                      }
                    })

                  }
                  // console.log(reader)
                  // if (reader[0] && reader[0] === "event:conversation.message.delta") {
                  // }


                  read();
                }).catch(err => {
                  console.error('Stream reading error:', err);
                });
              }

              read();
            } else {
              console.log(data);
            }
          })
          .catch(error => console.error('Error:', error));
      // #endif
      setTimeout(() => {
        _this.scrollTop = _this.scrollViewHeight + 200;
      }, 20);
      _this.userInput = [null, null, null];

    },

    focusTextarea(e) {
      this.inputBottom = e.detail.height;
      this.scrollTop += 1; //滚到底部
    },
    blurTextarea(e) {
      this.inputBottom = uni.getSystemInfoSync().safeAreaInsets.bottom;
      this.scrollTop += 1; //滚到底部
    }
  }
};
</script>

<style lang="scss" scoped>
.mes-content ::v-deep.parse {
  white-space: break-spaces;
}

.chat-wrapper {
  // flex-grow: 1;
  // display: flex;
  // flex-direction: column;
  // overflow: hidden;
  .container {
    width: 100vw;
    box-sizing: border-box;
    padding-bottom: 60px;
    display: flex;
    flex-direction: column;

    flex-grow: 1;
    overflow: hidden;
    // overflow: auto;
    position: relative;

    .my-bg {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }

    .Scroll {
      flex-grow: 1;
      padding-bottom: 50rpx;
    }

    .chatList {
      margin-top: 10px;
      padding: 0px 10px;

      .message {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;

        &.mes-left {
        }

        &.mes-right {
          display: flex;
          flex-direction: row-reverse;
        }

        .mes-content {
          margin-right: 6px;
          margin-left: 6px;
          background: #f5f6f7;
          padding: 8px;
          border-radius: 8px;
        }
      }
    }

    .header {
      flex-shrink: 0;
      padding: 0px 40rpx 32rpx 40rpx;
    }

    .content {
      flex-grow: 1;
      overflow: auto;

      .message {
        margin: 0px 40rpx 32rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .message-content {
          width: auto;
          max-width: calc(100vw - 80rpx);
          word-wrap: break-word;
          box-sizing: border-box;
          padding: 32rpx;
          line-height: 48rpx;
          background: pink;
          border-radius: 16rpx 0px 16rpx 16rpx;
        }

        .message-time {
          line-height: 32rpx;
          margin-top: 16rpx;
        }
      }
    }
  }

  .bottom-textarea {
    position: fixed;
    bottom: 0px;
    left: 0px;
    right: 0px;

    .content {
      display: flex;
      align-items: center;
      background-color: #f2f2f2;
      padding: 8px 8px;

    }

    .btn-box {
      display: flex;
      align-items: center;
      white-space: nowrap;
      padding: 8px 8px;

      .btn {
        display: flex;
        align-items: center;
        border-radius: 10rpx;
        background: #fff;
        padding: 5rpx 10rpx;
        color: #000;
        font-size: 26rpx;
      }

      .icon {
        width: 30rpx;
        height: 30rpx;
        margin-right: 5rpx;
      }
    }

    .textarea-container {
      flex: 1;
      min-height: 30rpx;
      background: rgba(255, 255, 255, 1);
      border-radius: 8rpx;
      box-sizing: border-box;
      padding: 8rpx 16rpx;

      > textarea {
        max-height: 250rpx;
        font-size: 36rpx;
        color: rgba(8, 8, 8, 1);
        width: auto;
      }
    }

    .tul-icon-wr {
      margin-left: 8px;
    }
  }
}

.yin-yong {
  margin-top: 10rpx;

  .tit {
    display: flex;
    align-items: center;

    .icon {
      width: 20rpx;
      height: 20rpx;
      margin-right: 10rpx;
    }

    .msg {
      font-size: 24rpx;
      color: #777;
      margin-left: 15rpx;
      margin-right: 15rpx;
    }

    .line {
      flex: 1;
      height: 1px;
      background: #EBEBEB;
    }
  }

  .content {
    margin-top: 10rpx;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .item {
      border-radius: 10rpx;
      border: 1px solid #EBEBEB;
      padding: 5rpx 10rpx;
      color: #777;
      font-size: 24rpx;
      display: flex;
      align-items: center;
      white-space: nowrap;
      margin-right: 10rpx;
      margin-top: 10rpx;

      .icon {
        width: 20rpx;
        height: 20rpx;
      }
    }
  }

  .tips {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .t {
      border-radius: 10rpx;
      border: 1px solid #007aff;
      padding: 5rpx 10rpx;
      margin-right: 10rpx;
      margin-top: 10rpx;
      color: #007aff;
      font-size: 28rpx;
    }
  }

}

.tui-modal-custom {
  display: flex;
  padding: 40rpx 0;
}

.border-b {
  border-bottom: 1px solid #e1e1e1;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;

  &:last-child {
    border: none;
  }
}

//
//.number-content{
//  display: flex;
//}
//
//.textarea{
//  height: 125px!important;
//}

</style>
